package com.niit.galuser.controller;


import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import com.niit.entity.Game;
import com.niit.entity.User;
import com.niit.galuser.service.impl.UserServiceImpl;
import com.niit.galuser.service.impl.VoteServiceImpl;
import com.niit.utils.CommonResult;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.servlet.http.HttpSession;
import javax.websocket.server.PathParam;
import java.util.List;

@RestController
@RequestMapping("/user")
public class UserController {
    @Resource
    private UserServiceImpl userService;
    @Resource
    private VoteServiceImpl voteService;

    @GetMapping("/sendMsg")
    @HystrixCommand( fallbackMethod = "blow",commandProperties = {
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "5000")
    })
    public CommonResult sendMsg(HttpSession session,@PathParam("email") String email) throws MessagingException {
        userService.sendMsg(session,email);
        return new CommonResult(200,"发送成功");
    }
    public CommonResult<String> blow(HttpSession session,String addr){
        return new CommonResult(400,"服务器繁忙！！！发送失败！！！");
    }

    @GetMapping ("getInfo")
    public CommonResult<User> getUser(HttpSession session){
        User user = (User) session.getAttribute("user");
        return new CommonResult<User>(200,"查询成功",user);
    }


    @PostMapping("setInfo")
    public CommonResult setInfo(@RequestBody User user,HttpSession session){
        User oldUser = (User) session.getAttribute("user");
        user.setUid(oldUser.getUid());
        userService.setInfo(user);
        User newUser = userService.findUserById(oldUser.getUid());
        session.setAttribute("user",newUser);
        return new CommonResult(200,"设置成功");
    }

    @GetMapping("upvote")
    public CommonResult<List<Game>> upvoteGames(HttpSession session){
        User user = (User) session.getAttribute("user");
        List<Game> games = voteService.findvoteGemes(user.getUid());
        return new CommonResult<List<Game>>(200,games.size()+"",games);
    }

    @GetMapping("collect")
    public CommonResult<List<Game>> collectGames(HttpSession session){
        User user = (User) session.getAttribute("user");
        List<Game> games = voteService.findCollectGames(user.getUid());
        return new CommonResult<List<Game>>(200,games.size()+"",games);
    }


}
